package com.yuki.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.yuki.api.common.CommonPage;
import com.yuki.api.model.UmsLogType;
import com.yuki.api.model.UmsLogTypeExample;
import com.yuki.api.model.UmsUserView;
import com.yuki.api.service.IUserViewService;
import com.yuki.provider.mapper.UmsLogTypeMapper;
import com.yuki.provider.mapper.redis.mapper.RedisMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: Yuki Tadayoshi
 * @time: 2021/4/2 9:30
 */
@Service(
        version = "1.0.0",
        interfaceName = "com.yuki.api.service.IUserViewService",
        interfaceClass = IUserViewService.class
)
@Transactional
public class UserUVServiceImpl implements IUserViewService {

    @Autowired
    private UmsLogTypeMapper typeMapper;

    @Autowired
    private RedisMapper redisMapper;

    @Override
    public CommonPage listUV(String start, String end, String type) {
        List uvList = forDate(start, end, type);
        return CommonPage.restPage(uvList);
    }

    public List<UmsUserView> forDate(String start, String end, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-Mm-dd");
        List<UmsUserView> uvList = new ArrayList<>();
        try {
            Date d1 = sdf.parse(start);
            Date d2 = sdf.parse(end);
            Calendar dd = Calendar.getInstance();
            Date tmp = d1;
            while (tmp.getTime() <= d2.getTime()) {
                tmp = dd.getTime();
                Set<Object> s = redisMapper.getAllKeys(sdf.format(tmp) + "_" + type);
                s.forEach(c -> {
                    int count = Integer.parseInt(redisMapper.get(c.toString()).toString());
                    uvList.add(new UmsUserView(c.toString().substring(0, 10), count));
                });
                dd.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uvList;
    }

    @Override
    public CommonPage listTypeUV() throws Exception {
        UmsLogTypeExample example = new UmsLogTypeExample();
        example.createCriteria().andFlagEqualTo(1);
        List<UmsLogType> list = typeMapper.selectByExample(example);
        return CommonPage.restPage(list);
    }
}
